<template>
    <el-form label-width="80px">
        <el-form-item label="SPU名称">
            <el-input placeholder="SPU名称" v-model="spuInfo.spuName"></el-input>
        </el-form-item>

        <el-form-item label="品牌">
            <el-select placeholder="请选择" v-model="spuInfo.tmId">
                <el-option v-for="item in tmList" :key="item.id" :value="item.id" :label="item.tmName"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="SPU描述">
            <el-input v-model="spuInfo.description" type="textarea" rows="6" placeholder="SPU描述"></el-input>
        </el-form-item>

        <el-form-item label="SPU图片">
            <el-upload v-model:file-list="spuImageList" :action="`${baseUrl}/admin/product/upload`"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" list-type="picture-card">
                <el-icon>
                    <Plus />
                </el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
        </el-form-item>

        <el-form-item label="销售属性">
            <el-select v-model="tempSaleAttr" :placeholder="`还有${unUsedSaleAttrList.length}未选择`">
                <el-option v-for="item in unUsedSaleAttrList" :key="item.id" :value="`${item.id}:${item.name}`"
                    :label="item.name">
                </el-option>
            </el-select>
            <el-button :disabled="!tempSaleAttr" type="primary" @click="addSaleAttr">添加销售属性</el-button>
        </el-form-item>

        <el-form-item>
            <el-table :data="spuSalseAttrList" border stripe>
                <el-table-column type="index" width="80" align="center" label="序号" />
                <el-table-column label="属性名" prop="saleAttrName" />
                <el-table-column label="属性值名称列表">
                    <template #="{ row }">
                        <el-tag v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag.id" type="success"
                            size="normal" closable @close="row.spuSaleAttrValueList.splice(index, 1)">{{
                                    tag.saleAttrValueName
                            }}</el-tag>
                        <el-button v-if="!row.isEdit" type="primary" size="small" @click="changeToEdit(row)">添加
                        </el-button>
                        <el-input v-else ref="inputEle" v-model="inputValue" placeholder="请选择" size="normal"
                            @blur="changeToLook(row)">
                        </el-input>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template v-slot="{ $index }">
                        <el-button type="danger" icon="ele-Delete" @click="spuSalseAttrList.splice($index, 1)">
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-form-item>

        <el-form-item label="">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button @click="emit('setState', 0)">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
import { requestBaseSaleAttrList, requestSaveSpuInfo, requestSpuImageList, requestSpuSaleAttrList, requestUpdateSpuInfo, type BaseSaleAttrListType, type SpuImageListType, type SpuSaleAttrItemType, type SpuSaleAttrListType, type supInfoType } from "@/api/spu";
import { defineComponent } from "vue";
import { requestAllTmList, type TmListType } from '@/api/tradmark';
import { ElMessage } from 'element-plus';

export default defineComponent({
    name: "SupFrom",
});
</script>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
const baseUrl = import.meta.env.VITE_API_URL;

//1.接收自定义事件，点击切换组件
const emit = defineEmits<{
    (event: "setState", state: number, row?: supInfoType): void
}>()

//2.接收spuInfo
const props = defineProps<{
    spuInfo: supInfoType
}>()

//定义初始化请求需要的数据
const tmList = ref<TmListType[]>()
const allSalseAttrList = ref<BaseSaleAttrListType>([])
const spuImageList = ref<SpuImageListType>([])
const spuSalseAttrList = ref<SpuSaleAttrListType>([])

//3.初始化请求需要的数据
const useData = async () => {
    try {
        if (props.spuInfo.id) {
            //如果是修改就发送4个请求
            const promise1 = requestAllTmList()
            const promise2 = requestBaseSaleAttrList()
            const promise3 = requestSpuImageList(props.spuInfo.id)
            const promise4 = requestSpuSaleAttrList(props.spuInfo.id)
            //发送4个请求
            const result = await Promise.all([promise1, promise2, promise3, promise4])
            tmList.value = result[0]
            allSalseAttrList.value = result[1]
            spuImageList.value = result[2]
            //处理图片列表
            spuImageList.value.forEach((item) => {
                item.name = item.imgName
                item.url = item.imgUrl
            })
            spuSalseAttrList.value = result[3]
            //处理spu销售属性列表数据
            spuSalseAttrList.value.forEach((item) => {
                item.isEdit = false
            })
        } else {
            //如果是添加发送2个请求
            const result1 = await requestAllTmList()
            tmList.value = result1
            const result2 = await requestBaseSaleAttrList()
            allSalseAttrList.value = result2
        }
    } catch (error) {
        //失败提示
        ElMessage.error("初始化请求失败!")
    }
}
onMounted(() => {
    useData()
});

//4.计算没有选择的销售属性列表
const unUsedSaleAttrList = computed(() => {
    return allSalseAttrList.value.filter((item) => {
        return spuSalseAttrList.value.every((item1) => {
            return item.name !== item1.saleAttrName
        })
    })
})

//定义数据保存临时销售属性
const tempSaleAttr = ref("")
//5.点击添加销售属性的回调
const addSaleAttr = () => {
    //拿到临时销售属性的值
    const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(":")
    //创建一个销售属性对象
    const newSaleAttr = {
        baseSaleAttrId: +baseSaleAttrId,
        saleAttrName: saleAttrName,
        spuSaleAttrValueList: []
    }
    //插入
    spuSalseAttrList.value.push(newSaleAttr)
    //清空临时属性
    tempSaleAttr.value = ""
}

//获取input实例
const inputEle = ref<HTMLInputElement>()
//6.点击添加属性值按钮的逻辑
const changeToEdit = (row: SpuSaleAttrItemType) => {
    row.isEdit = true
    //获取焦点
    nextTick(() => {
        inputEle.value?.focus()
    })
}

//定义数据保存输入框的值
const inputValue = ref("")
//7.失去焦点的回调
const changeToLook = (row: SpuSaleAttrItemType) => {
    //判断是否为空
    if (!inputValue.value) {
        row.isEdit = false
        ElMessage.error("输入为空!")
        return;
    }

    //判断重复
    const isRepect = row.spuSaleAttrValueList.some((item) => {
        return item.saleAttrValueName === inputValue.value
    })
    if (isRepect) {
        row.isEdit = false
        inputValue.value = ""
        ElMessage.error("输入重复!")
        return;
    }

    //输入正常创建属性值数据
    const newSaleAttrValue = {
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrName: row.saleAttrName,
        saleAttrValueName: inputValue.value
    }
    //插入到属性值列表
    row.spuSaleAttrValueList.push(newSaleAttrValue)

    //切换状态并清空临时值
    row.isEdit = false
    inputValue.value = ""
}

//8.点击保存的回调
const save = async () => {
    //处理图片列表数据
    const newSpuImageList = spuImageList.value.map((item) => {
        if (item.response) {
            return {
                imgName: item.name as string,
                imgUrl: item.response.data as string,
            }
        } else {
            return {
                imgName: item.name as string,
                imgUrl: item.url as string,
            }
        }
    })

    //处理销售属性列表数据
    spuSalseAttrList.value.forEach((item) => {
        delete item.isEdit
    })

    //赋值
    props.spuInfo.spuImageList = newSpuImageList
    props.spuInfo.spuSaleAttrList = spuSalseAttrList.value

    //提交数据发送请求
    try {
        if (props.spuInfo.id) {
            //修改
            await requestUpdateSpuInfo(props.spuInfo)
        } else {
            //新增操作
            await requestSaveSpuInfo(props.spuInfo);
        }
        ElMessage.success(props.spuInfo.id ? '修改spu成功!' : '添加spu成功!')
        //不管是新增还是修改都回到首页
        emit("setState", 0);
    } catch (error) {
        ElMessage.error(props.spuInfo.id ? '修改spu失败!' : '添加spu失败!')
    }

}



//照片墙逻辑
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

</script>